//除自身以外数组的乘积
//测试链接 https://leetcode.cn/problems/product-of-array-except-self/
public class ProductExceptSelf {
    public int[] productExceptSelf(int[] nums) {
        int n = nums.length;

        int[] f = new int[n];  //前缀积
        f[0] = nums[0];
        int[] g = new int[n];  //后缀积
        g[n-1] = nums[n-1];

        for(int i = 1, j = n-2; i < n; i++, j--){
            f[i] = f[i-1] * nums[i];
            g[j] = g[j+1] * nums[j];
        }

        int[] ret = new int[n];
        ret[0] = g[1];
        ret[n-1] = f[n-2];
        for(int i = 1; i < n-1; i ++){
            ret[i] = f[i-1] *  g[i+1];
        }

        return ret;
    }
}
